package com.tuniu.agents.impl.trip;

import com.tuniu.agents.advisor.AgentChatMemoryAdvisor;
import com.tuniu.agents.agent.AgentManager;
import com.tuniu.agents.agent.AgentManagerGroup;
import com.tuniu.agents.common.agent.TripAgent;
import com.tuniu.agents.common.entity.trip.ExtractResourceResponse;
import com.tuniu.agents.common.entity.trip.TripSummary;
import com.tuniu.agents.memory.MemoryManager;
import com.tuniu.agents.message.MessageMemoryManager;
import com.tuniu.agents.message.MessageSender;
import com.tuniu.agents.util.HttpManager;
import com.tuniu.agents.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.util.List;
import java.util.Map;

import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY;
@Slf4j
public class TripSummaryAgent extends TripAgent {
    private static final String TRAVEL_TEXT  = "travel_text";
    private static final String QUERY_STRING = "Please analyze the following travel document content and generate a detailed travel plan:";

    @Value("${aigc.agents.tools.trip.tripAgentResourceUrl}")
    private String RESOURCE_URL;

    @Autowired
    private HttpManager httpManager;
    

    private AgentManager agentManager;

    private MemoryManager memoryManager;

    private MessageSender messageSender;

    @Autowired
    private MessageMemoryManager messageMemoryManager;
    


    public TripSummaryAgent(AgentManagerGroup agentManagerGroup,
                            String agentId, String promptTemplateId) {
        super(agentManagerGroup, agentId, promptTemplateId);
        
    }


    @Override
    public String call(String conversationId, List<Message> messages, Map<String, Object> context) {
        String message = messages.get(0).getText();
        ChatResponse chatResponse = super.chatClient.prompt()
            .user(message) // Standard input format
            .advisors(a -> a.param(CHAT_MEMORY_CONVERSATION_ID_KEY, conversationId).
            param(AgentChatMemoryAdvisor.CHAT_MEMORY_AGENT_ID_KEY, this.agentId))
            .call()
            .chatResponse();
        TripSummary tripSummary = getTripSummary(chatResponse);
        ExtractResourceResponse extractResourceResponse = getResourceString(tripSummary);   
        return chatResponse.toString();
    }

    /**
     * Parse the travel information returned by the model
     */
    private TripSummary getTripSummary(ChatResponse chatResponse){
        String agentResult = chatResponse.getResult().getOutput().getText();
        TripSummary tripSummary = new TripSummary();
        
        // Extract JSON data using regex pattern
        String jsonPattern = "```json\\s*(\\{.*?\\})\\s*```";
        java.util.regex.Pattern pattern = java.util.regex.Pattern.compile(jsonPattern, java.util.regex.Pattern.DOTALL);
        java.util.regex.Matcher matcher = pattern.matcher(agentResult);
        
        if (matcher.find()) {
            String jsonString = matcher.group(1);
            try {
                tripSummary = JsonUtil.fromJson(jsonString, TripSummary.class);
                return tripSummary;
            } catch(Exception e) {
                log.error("Failed to parse travel information returned by the model", e);
            }
        } else {
            log.error("No JSON data found");
        }

        return tripSummary;
    }

    /**
     * Get resource string from trip summary
     * @param tripSummary
     * @return
     */
    private ExtractResourceResponse getResourceString(TripSummary tripSummary){
        log.info("URL: {}", RESOURCE_URL);
        log.info("Extracting resources: {}", JsonUtil.toJson(tripSummary.getResourceList()));
        ExtractResourceResponse result = httpManager.post(RESOURCE_URL, tripSummary.getResourceList(), ExtractResourceResponse.class);
        log.info("Resource extraction result: {}", JsonUtil.toJson(result));
        return result;
    }

   
}
